#include <algorithm>
#include <iostream>
#include <vector>
#include <unordered_set>
#include <numeric>
using namespace std;

vector<int> bucket;
vector<bool> vi;
vector<unordered_set<int>> track;
bool ans;

void dfs(int x, const int& k, vector<int>& nums, int start) {
    if (ans) return;
    if (x == k) {
        ans = 1;
        return;
    }

    if (bucket[x] == 0) { dfs(x + 1, k, nums, 0); }

    for (int i = start; i < nums.size(); i++) {
        if (vi[i] || nums[i] > bucket[x]) continue;
        if(i>=1 && nums[i] == nums[i-1] && !track[x].count(i-1) && !vi[i-1]) continue;
        vi[i] = 1;
        track[x].insert(i);
        bucket[x] -= nums[i];
        dfs(x, k, nums, i + 1);
        vi[i] = 0;
        track[x].erase(i);
        bucket[x] += nums[i];
    }
}

bool canPartitionKSubsets(vector<int>& nums, int k) {
    int sum = accumulate(nums.begin(), nums.end(), 0);
    if (sum % k) return 0;
    sort(nums.begin(), nums.end(), greater<int>());
    if (nums[0] > sum / k) return 0;
    int n = nums.size();
    bucket.resize(k, sum / k);
    vi.resize(n, 0);
    track.resize(k);
    dfs(0, k, nums, 0);
    return ans;
}








/**
 * @方法: 判断每个数应该放入的桶
 * @时间复杂度: o()
 * @空间复杂度: o()
 * @评价:   剪枝很重要
 */
int sum;
int buckets[20];
bool tag;
void dfs(int x, int k, vector<int>& nums, int side, int start) {
    if (x == nums.size()) {
        tag = 1;
        return;
    }
    int begin = 0;
    if(x-1 >= 0 && nums[x] == nums[x-1]) begin = start;
    for (int i = begin; i < k; i++) {
        if (nums[x] > side - buckets[i]) continue;
        buckets[i] += nums[x];
        dfs(x+1, k, nums, side, i);
        buckets[i] -= nums[x];
    }
    return;
}
bool canPartitionKSubsets(vector<int>& nums, int k) {
    for (int i = 0; i < nums.size(); i++) sum += nums[i];
    if (sum % k) return 0;
    sum /= k;
    sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; });
    if (nums[0] > sum) return 0;
    int cur = 0;
    while (nums[cur] == sum) cur++;
    vector<int> part(nums.begin() + cur, nums.end());
    dfs(0, k - cur, part, sum, 0);
    if (tag == 1) return 1;
    return 0;
}

int main() {
    // vector<int> nums{10, 1, 10, 9, 6, 1, 9, 5, 9, 10, 7, 8, 5, 2, 10, 8};
    // vector<int> nums{1 ,7, 2, 6, 4, 4, 3, 5};
    vector<int> nums{2, 2, 2, 2, 3, 4, 5};
    bool ans = canPartitionKSubsets(nums, 4);
    cout << ans << endl;
}